<?php

namespace Modules\DataAnalysis\Http\Controllers\Admin;

use App\Exceptions\BusinessException;
use App\Helpers\CodeResponse;
use App\Helpers\QueryBuilder;
use App\Http\Controllers\Admin\ApiController;
use App\Http\Resources\BaseResource;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Modules\DataAnalysis\Entities\Comment;
use Modules\DataAnalysis\Entities\Setting;
use Modules\DataAnalysis\Http\Requests\Admin\CommentRequest;

class CommentController extends ApiController
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(CommentRequest $request)
    {
        // 系统设置
        $settings = Setting::query()->get();
        $score_line = $settings->where('key', 'score_line')->first()->value;
        // 将分数线缓存一下【模型中使用】
        Cache::put('score_line', $score_line);

        $query = Comment::query()->where('video_id', $request->get('video_id'));
        if (!is_null($request->get('feeling'))) {
            if ($request->get('feeling') == 'positive') {
                // 积极
                $operator = '>=';
            } else {
                // 消极
                $operator = '<';
            }

            $query = $query->where('score', $operator, $score_line);
        }
        $data = QueryBuilder::for($query)
            ->fields()
            ->filters(['sex', 'nickname', 'district', 'content'])
            ->includes()
            ->sorts(['zan_count', 'score', 'comment_at'])
            ->page();
        return $this->success(BaseResource::collection($data));
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show(Comment $comment)
    {
        return $this->success($comment->load(['video', 'phrases']));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(CommentRequest $request, Comment $comment)
    {
        // 系统设置
        $settings = Setting::query()->get();
        $edit_comment_score = $settings->where('key', 'edit_comment_score')->first()->value;
        if (!$edit_comment_score) {
            throw new BusinessException(CodeResponse::REJECT_OPERATION, "不允许修改评论分数~");
        }

        $comment->score = $request->get('score');
        $comment->save();
        return $this->success($comment);
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy(Comment $comment)
    {
        DB::transaction(function () use ($comment) {
            $comment->phrases()->delete();
            $comment->delete();
        });

        return $this->noContent();
    }
}
